package com.wwm.makerandroid.makerandroid.View.Fragment;


import static com.wwm.makerandroid.makerandroid.Utils.DateUtil.showDateDialog;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import com.google.gson.Gson;
import com.lipiao.makerandroid.R;
import com.wwm.makerandroid.makerandroid.Bean.RespondBean.RecordBean2;

import com.wwm.makerandroid.makerandroid.MainActivity;
import com.wwm.makerandroid.makerandroid.Utils.DivisionModel;
import com.wwm.makerandroid.makerandroid.Utils.Divisions;
import com.wwm.makerandroid.makerandroid.Utils.HttpUtil;

import com.wwm.makerandroid.makerandroid.View.Adapter.ApplyRecordAdapter2;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.defaults.view.Division;
import top.defaults.view.DivisionPickerView;


//原始的四个碎片自带缓存 无需懒加载 也不会重复加载数据
public class TongjiFragment extends Fragment {

    static String userNumber;//账号
    Button btDate;
    Button saixuan;

//    EditText etJingguo;
//    自己写的省市区的下拉框
//    Spinner spSheng;
//    Spinner spShi;
//    Spinner spQu;

//    引入别人的省市区下拉框
    DivisionPickerView divisionPicker;
    Button diquText;
   private Unbinder unbinder;
    View rootView;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.rv_top_article)
    RecyclerView mRecyclerView;
    static Context mainActivity;
    List recordList;
    static ApplyRecordAdapter2 topArticleAdapter;
     static List<DivisionModel> divisions ;
    public static TongjiFragment newInstance(String userNumber, MainActivity context) {
        TongjiFragment fragment = new TongjiFragment();
        Bundle bundle = new Bundle();
        bundle.putString("userNumber", userNumber);
        mainActivity = context;
        String path = "/raw/area.json";
//        ClassPathResource resource = new ClassPathResource(path);

//        JSONObject jsonObject=dataJson;
//        解析成数组

        fragment.setArguments(bundle);
        return fragment;

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mainActivity = getContext();
        rootView = inflater.inflate(R.layout.fragment_tongji, container, false);
        //返回一个Unbinder值（进行解绑），注意这里的this不能使用getActivity()
        unbinder = ButterKnife.bind(this, rootView);
        assert getArguments() != null;//判空处理
        userNumber = getArguments().getString("userNumber");//获取账号
        divisionPicker=rootView.findViewById(R.id.divisionPicker);

        diquText=rootView.findViewById(R.id.text_diqu);
//        为地区选择器初始化数据
//        因为是单例 所以只要在mainActivity赋值一次在这就直接能拿到
        divisions = Divisions.get("");
        //        添加地区数据
        divisionPicker.setDivisions(divisions);
//        为地区选择器添加事件监听 当地区选择器改变时 为地区文本框赋值
        divisionPicker.setOnSelectedDateChangedListener(division ->
                diquText.setText(Division.Helper.getCanonicalName(division)));
//       为地区文本添加监听 当点击设置地区选择器是否显示
//        0显示  8不显示
//        divisionPicker->divisionPicker.setVisibility(8-divisionPicker.getVisibility())
        diquText.setOnClickListener(view -> divisionPicker
                .setVisibility(8-divisionPicker.getVisibility()));
        saixuan = rootView.findViewById(R.id.bt_shaixuan);
        btDate = rootView.findViewById(R.id.bt_time_tg);
        saixuan.setOnClickListener(mOnClickListener);
        btDate.setOnClickListener(mOnClickListener);
        return rootView;
    }


    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.bt_time_tg:
                    showDateDialog(v, btDate, "", mainActivity);
                    break;
                case R.id.bt_shaixuan:
                    String text = diquText.getText().toString();
                    String date = btDate.getText().toString();
                    //提交统计请求
                    Call<ResponseBody> call = HttpUtil.getUserService().tongji(date + ":00", text);
                    call.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            try {
                                if(response == null || response.body() == null){
                                    Log.d("筛选", "没有符合条件的数据");
                                    return;
                                }
                                String strBack = response.body().string();
                                //处理数据
                                JSONObject jsonObject;
                                jsonObject = new JSONObject(strBack);
                                Gson gson = new Gson();
                                RecordBean2 recordBean;
                                recordBean = gson.fromJson(jsonObject.toString(), RecordBean2.class);
                                System.out.println(recordBean);
                                recordList = recordBean.getData();
                                if(recordList==null){
                                    Toast.makeText(mainActivity, "没有符合条件的数据!", Toast.LENGTH_LONG).show();                                    return;
                                }
                                initRecordView();
                                //获取完数据后UI操作
                                //主线程将alertDialog提示隐藏
                                Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                    }
                                });
                            } catch (JSONException e) {
                                System.out.println(e);
                                Log.d("筛选", "数据成功");
                            } catch (IOException e) {
                                System.out.println(e);
                                e.printStackTrace();
                            }
                        }
                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                            Toast.makeText(mainActivity, t.getMessage(), Toast.LENGTH_LONG).show();
                            Log.d("test", "onResponse: error");
                        }
                    });
                    break;
                default:
                    break;
            }
        }
    };



    //    加载对应数据
    //初始化记录列表
    private void initRecordView() {
        //top rv
        mRecyclerView.setHasFixedSize(true);
        //平常的水平一个item布局的流
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        //设置预览信息
//实例化MyAdapter并传入mList对象
        //这里原本是文章列表的构造器直接拿来复用了
        topArticleAdapter = new ApplyRecordAdapter2(recordList);

//为RecyclerView对象mRecyclerView设置adapter
        mRecyclerView.setAdapter(topArticleAdapter);
    }


}
